///Users/rimi/Desktop/Go/Go!.xcodeproj
//  HQYHomePageViewController.m
//  Go!
//
//  Created by rimi on 16/7/7.
//  Copyright © 2016年 黄秋燕. All rights reserved.
//

#import "HQYHomePageViewController.h"
#import "HQYHomeScrollView.h"
#import <CoreLocation/CoreLocation.h> // 地图定位
#import "HQYGetLocationNetworkingManager.h" // 经纬度转地址
#import "NetWorkManager.h" // 网络请求
#import "HQYHomeFoodView.h" // 美食视图
#import "HQYHomeTourView.h" // 旅游视图
#import "HQYHomeHotelView.h" // 酒店视图
#import "HQYHomeBoutiqueRecommendView.h" // 分割视图
#import "HQYOffsetImageCell.h" // 开眼cell
#import "UIImageView+WebCache.h" // 图片缓存
#import "HQYHomeKeyEyesModel.h" // 开眼数据请求模型
#import "HQYHomeCellDetailViewController.h" // 点击开眼的详细页面
#import "HQYSearchViewController.h" // 搜索页面
#import "UIImage+GIF.h" // 加载动态图片的类目
#import "HQYQRCodeScanerViewController.h" // 二维码扫描

#define IMAGE_NUM self.imageNameArr.count

@interface HQYHomePageViewController () <CLLocationManagerDelegate, UITableViewDataSource, UITableViewDelegate>
{
    CLLocationManager *_locationManager; /**< 定位服务 */
}

@property (nonatomic, strong) UIScrollView *backgroundScrollView; /**< 背景底部滚动视图 */
@property (nonatomic, strong) HQYHomeScrollView *advertisementScrollView; /**< 首页顶部轮播图 */
@property (nonatomic, strong) UIView *initializeNavView; /**< 自定义导航 */
@property (nonatomic, strong) UIButton *locationBtn; /**< 左边定位按钮 */
@property (nonatomic, strong) UIButton *QRCodeBtn; /**< 右边二维码按钮 */
@property (nonatomic, strong) UIButton *shoppingCartBtn; /**< 右边购物车按钮 */

#pragma mark --选择按钮
@property (nonatomic, strong) UIView *selectButtonBackgroundView; /**< 选择按钮的背景视图 */
@property (nonatomic, strong) UIButton *foodSelectButton; /**< 美食选择 */
@property (nonatomic, strong) UIButton *tourSelectButton; /**< 周边游选择 */
@property (nonatomic, strong) UIButton *hotelSelectButton; /**< 酒店选择 */
@property (nonatomic, strong) UIButton *MineSelectButton; /**< 我的选择 */

#pragma mark --模仿粒子效果
@property (nonatomic, strong) UIView *grayView; /**< 粒子动画视图 */
@property (nonatomic, strong) CAEmitterLayer *emitterLayer; /**< 发射源图层 */

#pragma mark --首页上的各种视图
@property (nonatomic, strong) HQYHomeFoodView *foodView; /**< 美食视图 */
@property (nonatomic, strong) HQYHomeTourView *tourView; /**< 旅游视图 */
@property (nonatomic, strong) HQYHomeHotelView *hotelView; /**< 酒店视图 */
@property (nonatomic, strong) HQYHomeBoutiqueRecommendView *boutiqueRecommendView; /**< 分割视图 */

#pragma mark --开眼表格视图
@property (nonatomic, strong) UITableView *keyEyesTableView; /**< 开眼表格视图 */
@property (nonatomic, strong) HQYHomeKeyEyesModel *model; /**< 模型 */

@end

static HQYHomePageViewController *homeVc = nil;

@implementation HQYHomePageViewController
- (void)dealloc {
    // 移除观察者
    [self.model removeObserver:self forKeyPath:@"response"];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //导航栏透明
    self.navigationItem.title = @"";
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationValue:) name:@"sendCurrentCityName" object:nil];
    [_locationBtn setTitle:[[NSUserDefaults standardUserDefaults] objectForKey:currentCity_Name] forState:UIControlStateNormal];
    // 获得商家信息网络请求
    [self.model getList];
    [self.model addObserver:self forKeyPath:@"response" options:NSKeyValueObservingOptionNew context:nil];
}

#pragma mark - 简单单例
+ (HQYHomePageViewController *)shareHomeVc {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        homeVc = [[HQYHomePageViewController alloc] init];
    });
    
    return homeVc;
}

// 通知监听回调(定位成功)
- (void)notificationValue:(NSNotification *)notif {
    NSString *str = notif.object;
    [_locationBtn setTitle:str forState:UIControlStateNormal];
    
    // 获得商家信息网络请求
    [self.model getList];
    [self.keyEyesTableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initializeUserInterface];
    [self initializeNavigation];
}

#pragma mark - initialize
// 监听到状态变化会执行该方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"response"]) {
        [self.model getDataArray];
        [self.keyEyesTableView reloadData];
    }
}

/**< 初始化用户界面 */
- (void)initializeUserInterface {
    self.view.backgroundColor = ColorWith(232, 232, 232);
    //取消滚动视图对于导航条的自动适配
    self.automaticallyAdjustsScrollViewInsets = NO;

    [self.view addSubview:self.backgroundScrollView];
    [self.backgroundScrollView addSubview:self.advertisementScrollView];
    [self.backgroundScrollView addSubview:self.selectButtonBackgroundView];
    
    /**< 选择按钮 */
    [self.selectButtonBackgroundView addSubview:self.foodSelectButton];
    [self.selectButtonBackgroundView addSubview:self.tourSelectButton];
    [self.selectButtonBackgroundView addSubview:self.hotelSelectButton];
    [self.selectButtonBackgroundView addSubview:self.MineSelectButton];
    
    /**< 视图 */
    [self.backgroundScrollView addSubview:self.foodView];
    [self.backgroundScrollView addSubview:self.tourView];
    [self.backgroundScrollView addSubview:self.hotelView];
    [self.backgroundScrollView addSubview:self.boutiqueRecommendView];
    [self.backgroundScrollView addSubview:self.keyEyesTableView];
    
    self.backgroundScrollView.contentSize = CGSizeMake(0, CGRectGetMaxY(self.keyEyesTableView.frame)); //滚动范围

    /**< 粒子动画视图 */
    UIView *grayView = [[UIView alloc] initWithFrame:self.view.bounds];
    grayView.backgroundColor = [UIColor clearColor];
    self.grayView = grayView;
    [self.backgroundScrollView addSubview:self.grayView];
    self.grayView.hidden = YES;
}

#pragma mark - 自定义导航设置
- (void)initializeNavigation {
    _initializeNavView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 55)];
    _initializeNavView.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
    [self.view addSubview:_initializeNavView];
    // 设置状态栏模式
//    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    
    // 左边定位按钮
    _locationBtn = [self initializeNavButtonSetWithCenterX:Size_W(22) imageName:@"定位"];
    _locationBtn.bounds = CGRectMake(0, 0, Size_W(60), Size_H(22));
    _locationBtn.center = CGPointMake(Size_W(41), CGRectGetMidY(_initializeNavView.frame) + Size_H(10));
    _locationBtn.titleLabel.font = [UIFont boldSystemFontOfSize:Font(14)];
    [_locationBtn addTarget:self action:@selector(clickLocationBtn) forControlEvents:UIControlEventTouchUpInside];
    
    // 中间搜索按钮
    // 先创建一个输入框
    {
        UITextField *textField = [[UITextField alloc] init];
        textField.bounds = CGRectMake(0, 0, Size_W(240), Size_H(25));
        textField.center = CGPointMake(CGRectGetMidX(_initializeNavView.frame), CGRectGetMidY(_initializeNavView.frame) + Size_H(10));
        textField.backgroundColor = [UIColor colorWithWhite:1 alpha:0.6];
        
        // 提示文本字体、颜色、大小
        textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"搜索商家或地点" attributes:@{NSForegroundColorAttributeName:[UIColor grayColor], NSFontAttributeName:[UIFont systemFontOfSize:Font(14)]}];
        
        // 占位图片
        textField.leftViewMode = UITextFieldViewModeAlways;
        UIImageView *imgView   = [[UIImageView alloc] initWithFrame:CGRectMake(20, 8, 15, 15)];
        imgView.contentMode = UIViewContentModeCenter;
        imgView.image          = IMAGE(@"搜索-灰");
        imgView.contentMode    = UIViewContentModeScaleToFill;
        textField.leftView     = imgView;
        [_initializeNavView addSubview:textField];
        
        UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
        searchButton.frame = textField.bounds;
        [searchButton addTarget:self action:@selector(clickSearchButton) forControlEvents:UIControlEventTouchUpInside];
        [textField addSubview:searchButton];
    }
    
    // 右边二维码按钮
    _QRCodeBtn = [self initializeNavButtonSetWithCenterX:(ScreenW - Size_W(22)) imageName:@"二维码"];
    [_QRCodeBtn addTarget:self action:@selector(clickQRCodeBtn) forControlEvents:UIControlEventTouchUpInside];
    
    // 右边购物车按钮
    _shoppingCartBtn = [self initializeNavButtonSetWithCenterX:CGRectGetMinX(_QRCodeBtn.frame) - Size_W(22) imageName:@"购物车"];
    [_shoppingCartBtn addTarget:self action:@selector(clickShoppingCartBtn) forControlEvents:UIControlEventTouchUpInside];
    
    [_initializeNavView addSubview:_locationBtn];
    [_initializeNavView addSubview:_QRCodeBtn];
    [_initializeNavView addSubview:_shoppingCartBtn];
}

#pragma mark --导航栏上按钮公共方法
- (UIButton *)initializeNavButtonSetWithCenterX:(CGFloat)centerX
                                      imageName:(NSString *)imageName
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.bounds = CGRectMake(0, 0, Size_W(22), Size_H(22));
    btn.center = CGPointMake(centerX, CGRectGetMidY(_initializeNavView.frame) + Size_H(10));
    [btn setImage:IMAGE(imageName) forState:UIControlStateNormal];
    return btn;
}

#pragma mark --左边定位按钮监听
- (void)clickLocationBtn {
    if (![CLLocationManager locationServicesEnabled]) { // 不支持定位
        // 弹框提示用户：设备不支持定位
        [Tools showAlertWithMessage:@"您的设备暂未开启定位服务!"];
        
        return;
    }
    // 初始化定位服务
    _locationManager = [[CLLocationManager alloc] init];
    // 请求用户授权
    [_locationManager requestAlwaysAuthorization];
    // 获取定位的状态（成功/失败）
    _locationManager.delegate = self;
    [_locationManager startUpdatingLocation];
}

#pragma mark --定位失败
- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
    [Tools showAlertWithMessage:@"定位失败"];
}

#pragma mark --定位成功
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    // 获取最新的定位信息
    CLLocation *location = locations.lastObject;
    
    // 停止定位
    [_locationManager stopUpdatingLocation];
    
    // 根据经纬度获得城市
    [HQYGetLocationNetworkingManager postWithParams:@{@"lng":[NSString stringWithFormat:@"%f", location.coordinate.longitude], @"lat":[NSString stringWithFormat:@"%f", location.coordinate.latitude], @"from":@"5"} Successblock:^(id responseObject) {
        // 获得当前定位城市
        NSString *city = responseObject[@"showapi_res_body"][@"addressComponent"][@"city"];
        [NetWorkManager getWithURL:@"cities" urlParam:nil successBlock:^(id responseObject) {
            // 获得所有的城市
            NSArray *citiesArray = [responseObject objectForKey:@"cities"];
            [[NSUserDefaults standardUserDefaults] setObject:citiesArray forKey:AllCitiesArray];
            // 查找是否有当前城市
            for (NSDictionary *obj in citiesArray) {
                if ([obj[@"city_name"] isEqualToString:city]) {
                    NSLog(@"%@", obj[@"city_name"]);
                    // 上一次定位的位置
                    NSString *lastCityId = [[NSUserDefaults standardUserDefaults] objectForKey:currentCity_ID];
                    // 判断上次的位置和本次定位的位置是否相同
                    if ([lastCityId isEqualToString:[NSString stringWithFormat:@"%@", obj[@"city_id"]]]) { // 相同
                        [self.locationBtn setTitle:[NSString stringWithFormat:@"%@", obj[@"short_name"]] forState:UIControlStateNormal];
                        return;
                    }
                    else {
                        // 弹窗：是否切换城市
                        {
                            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您当前位置已更改，是否切换当前城市？" preferredStyle:UIAlertControllerStyleAlert];
                            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                                // 保存当前的城市ID
                                [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%@", obj[@"city_id"]] forKey:currentCity_ID];
                                [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%@", obj[@"short_name"]] forKey:currentCity_Name];
                                /**< 通知传值 */
                                [[NSNotificationCenter defaultCenter] postNotificationName:@"sendCurrentCityName" object:obj[@"short_name"]];
                            }]];
                            [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
                            [self presentViewController:alert animated:YES completion:nil];
                        }
                    }
                }
            }
        } FailureBlock:nil];
        
    } Failblock:nil];
}

#pragma mark --搜索按钮监听
- (void)clickSearchButton {
    HQYSearchViewController *detailVC = [[HQYSearchViewController alloc] init];
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark --右边购物车按钮监听
- (void)clickShoppingCartBtn {
    
}

#pragma mark --右边二维码按钮监听
- (void)clickQRCodeBtn {
    HQYQRCodeScanerViewController *QRCodeVc = [[HQYQRCodeScanerViewController alloc] init];
    [self.navigationController pushViewController:QRCodeVc animated:NO];
}

#pragma mark - 粒子动画
- (void)emitterAnimationWithImage:(NSString *)image {
    //发射源
    CAEmitterLayer * emitter = [CAEmitterLayer layer];
    emitter.frame = CGRectMake(0, 0, CGRectGetWidth(self.grayView.frame), CGRectGetHeight(self.grayView.frame));
    [self.grayView.layer addSublayer:self.emitterLayer = emitter];
    //发射源形状
    emitter.emitterShape = kCAEmitterLayerCircle;
    //发射模式
    emitter.emitterMode = kCAEmitterLayerOutline;
    //发射位置
    emitter.emitterPosition = CGPointMake(ScreenW * 0.5, 0);
    //发射源尺寸大小
    emitter.emitterSize = CGSizeMake(20, 20);
    
    // 从发射源射出的粒子
    {
        CAEmitterCell * cell = [CAEmitterCell emitterCell];
        cell.name = @"kHQYShapeKey";
        //粒子要展现的图片
        cell.contents = (__bridge id)IMAGE(image).CGImage;
        //粒子透明度在生命周期内的改变速度
        cell.alphaSpeed = -0.5;
        //生命周期
        cell.lifetime = 3.0;
        //粒子产生系数(粒子的速度乘数因子)
        cell.birthRate = 0;
        //粒子速度
        cell.velocity = 300;
        //速度范围
        cell.velocityRange = 100;
        //周围发射角度
        cell.emissionRange = M_PI / 8;
        //发射的z轴方向的角度
        cell.emissionLatitude = -M_PI;
        //x-y平面的发射方向
        cell.emissionLongitude = -M_PI / 2;
        //粒子y方向的加速度分量
        cell.yAcceleration = 250;
        emitter.emitterCells = @[cell];
    }
}

- (void)beginAnimation {
    __weak typeof(self) weakSelf = self;
    self.grayView.hidden = NO;
    [UIView animateWithDuration:0.5f delay:0 usingSpringWithDamping:0.3 initialSpringVelocity:5 options:UIViewAnimationOptionCurveLinear animations:^{
        CABasicAnimation * effectAnimation = [CABasicAnimation animationWithKeyPath:@"emitterCells.kHQYShapeKey.birthRate"];
        effectAnimation.fromValue = [NSNumber numberWithFloat:30];
        effectAnimation.toValue = [NSNumber numberWithFloat:0];
        effectAnimation.duration = 0.0f;
        effectAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
        [weakSelf.emitterLayer addAnimation:effectAnimation forKey:nil];
        //放大动画
        {
            CABasicAnimation * aniScale = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
            aniScale.fromValue = [NSNumber numberWithFloat:0.1];
            aniScale.toValue = [NSNumber numberWithFloat:1.0];
            aniScale.duration = 1.5;
            aniScale.delegate = self;
            aniScale.removedOnCompletion = NO;
            aniScale.repeatCount = 1;
            [weakSelf.grayView.layer addAnimation:aniScale forKey:@"babyCoin_scale"];
        }
    } completion:^(BOOL finished) {
        
    }];
}

/**< 动画结束代理方法 */
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    if (anim == [self.grayView.layer animationForKey:@"babyCoin_scale"]) {
        self.grayView.hidden = YES;
    }
}


#pragma mark - <UITableViewDataSource, UITableViewDelegate>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // 更新表格和滚动视图的大小、滚动范围
    self.keyEyesTableView.frame = CGRectMake(0, tableView_Interval + CGRectGetMaxY(self.boutiqueRecommendView.frame), ScreenW, Size_H(180) * [self.model getNumberOfRows]);
    self.backgroundScrollView.contentSize = CGSizeMake(0, CGRectGetMaxY(self.keyEyesTableView.frame)); //滚动范围
    
    return [self.model getNumberOfRows];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HQYOffsetImageCell *cell  = [tableView dequeueReusableCellWithIdentifier:@"123" forIndexPath:indexPath];
    NSArray *array = [self.model getDataArray];
    // SDWebImage 异步加载图片 placeholderImage：在图片还未加载时，一个现实图片占位
    [cell.pictureView sd_setImageWithURL:[NSURL URLWithString:array[indexPath.row][@"icon"]] placeholderImage:[UIImage imageNamed:@"等待中"]];
    cell.titleLabel.text   = array[indexPath.row][@"description"];
    return cell;
}

// 将要显示cell时调用
- (void)tableView:(UITableView *)tableView willDisplayCell:(HQYOffsetImageCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // 滚动视差效果实现
    [cell cellOffset];
}

// 设置cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return Size_H(180);
}

// 点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *array = [self.model getDataArray];
    HQYHomeCellDetailViewController *detailVC = [[HQYHomeCellDetailViewController alloc] init];
    detailVC.dict = array[indexPath.row];
    detailVC.url = array[indexPath.row][@"url"];
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - <UIScrollViewDelegate>
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y <= 0 ) {
        scrollView.bounces = NO;
        self.initializeNavView.backgroundColor = [UIColor clearColor];
        [self.locationBtn setImage:IMAGE(@"定位") forState:UIControlStateNormal];
        [self.locationBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.QRCodeBtn setImage:IMAGE(@"二维码") forState:UIControlStateNormal];
        [self.shoppingCartBtn setImage:IMAGE(@"购物车") forState:UIControlStateNormal];
        
    }
    else if (scrollView.contentOffset.y > 40) {
        [UIView animateWithDuration:1.0 animations:^{
            self.initializeNavView.backgroundColor = [UIColor colorWithWhite:1 alpha:0.7];
            [self.locationBtn setImage:IMAGE(@"定位-红") forState:UIControlStateNormal];
            [self.locationBtn setTitleColor:ColorWith(246, 83, 53) forState:UIControlStateNormal];
            [self.QRCodeBtn setImage:IMAGE(@"二维码-红") forState:UIControlStateNormal];
            [self.shoppingCartBtn setImage:IMAGE(@"购物车-红") forState:UIControlStateNormal];
        }];
    }
    else {
        scrollView.bounces = YES;
    }
    
    // 获取可以见到的 cell,让图片在cell坐标改变的时候偏移
    NSArray<HQYOffsetImageCell *> *array = [self.keyEyesTableView visibleCells];
    [array enumerateObjectsUsingBlock:^(HQYOffsetImageCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj cellOffset];
        
    }];
}

#pragma mark - Getter
/**< 背景底部滚动视图 */
- (UIScrollView *)backgroundScrollView {
    if (!_backgroundScrollView) {
        _backgroundScrollView = [[UIScrollView alloc] init];
        _backgroundScrollView.frame = CGRectMake(0, 0, ScreenW, ScreenH - 49);
        //关闭弹簧效果
        _backgroundScrollView.bounces = NO;
        _backgroundScrollView.alwaysBounceHorizontal = NO;
        _backgroundScrollView.showsHorizontalScrollIndicator = NO;
        _backgroundScrollView.delegate = self;
        // 预设偏移量
//        _backgroundScrollView.contentSize = CGSizeMake(0, 2000);
    }
    return _backgroundScrollView;
}

/**< 首页顶部轮播图 */
- (HQYHomeScrollView *)advertisementScrollView {
    if (!_advertisementScrollView) {
        _advertisementScrollView = [[HQYHomeScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, SCROLL_VIEW_H)];
        _advertisementScrollView.vc = self;
    }
    
    return _advertisementScrollView;
}

/**< 选择按钮的背景视图 */
- (UIView *)selectButtonBackgroundView {
    if (!_selectButtonBackgroundView) {
        _selectButtonBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.advertisementScrollView.frame), ScreenW, ScreenW / 4)];
        _selectButtonBackgroundView.backgroundColor = [UIColor whiteColor];
    }
    return _selectButtonBackgroundView;
}

/**< 美食选择 */
- (UIButton *)foodSelectButton {
    if (!_foodSelectButton) {
        _foodSelectButton = [self initializeSelectButtonWithTitle:@"美食" image:IMAGE(@"首页-美食-1") locationX: ScreenW/8];
    }
    return _foodSelectButton;
}

/**< 周边游选择 */
- (UIButton *)tourSelectButton {
    if (!_tourSelectButton) {
        _tourSelectButton = [self initializeSelectButtonWithTitle:@"旅游" image:IMAGE(@"首页-旅游-1") locationX:ScreenW/8 + ScreenW/4];
    }
    return _tourSelectButton;
}

/**< 酒店选择 */
- (UIButton *)hotelSelectButton {
    if (!_hotelSelectButton) {
        _hotelSelectButton = [self initializeSelectButtonWithTitle:@"酒店" image:IMAGE(@"首页-酒店-1") locationX:ScreenW/8 + ScreenW/2];
    }
    return _hotelSelectButton;
}

/**< 我的选择 */
- (UIButton *)MineSelectButton {
    if (!_MineSelectButton) {
        _MineSelectButton = [self initializeSelectButtonWithTitle:@"我的" image:IMAGE(@"首页-我的-1") locationX:ScreenW-ScreenW/8];
    }
    return _MineSelectButton;
}

/**< 美食视图 */
- (HQYHomeFoodView *)foodView {
    if (!_foodView) {
        // 关联xib
        _foodView = (HQYHomeFoodView *)[[[NSBundle mainBundle] loadNibNamed:@"HQYHomeFoodView" owner:self options:nil] firstObject];
        _foodView.frame = CGRectMake(0, tableView_Interval + CGRectGetMaxY(self.selectButtonBackgroundView.frame), ScreenW, Size_H(200));
    }
    return _foodView;
}

/**< 旅游视图 */
- (HQYHomeTourView *)tourView {
    if (!_tourView) {
        _tourView = (HQYHomeTourView *)[[[NSBundle mainBundle] loadNibNamed:@"HQYHomeTourView" owner:self options:nil] firstObject];
        _tourView.frame = CGRectMake(0, tableView_Interval + CGRectGetMaxY(self.foodView.frame), ScreenW, Size_H(200));
    }
    return _tourView;
}

/**< 旅游视图 */
- (HQYHomeHotelView *)hotelView {
    if (!_hotelView) {
        _hotelView = (HQYHomeHotelView *)[[[NSBundle mainBundle] loadNibNamed:@"HQYHomeHotelView" owner:self options:nil] firstObject];
        _hotelView.frame = CGRectMake(0, tableView_Interval + CGRectGetMaxY(self.tourView.frame), ScreenW, Size_H(200));
    }
    return _hotelView;
}

/**< 分割视图 */
- (HQYHomeBoutiqueRecommendView *)boutiqueRecommendView {
    if (!_boutiqueRecommendView) {
        _boutiqueRecommendView = (HQYHomeBoutiqueRecommendView *)[[[NSBundle mainBundle] loadNibNamed:@"HQYHomeBoutiqueRecommendView" owner:self options:nil] firstObject];
        _boutiqueRecommendView.frame = CGRectMake(0, tableView_Interval + CGRectGetMaxY(self.hotelView.frame), ScreenW, Size_H(20));
    }
    return _boutiqueRecommendView;
}

/**< 开眼表格视图 */
- (UITableView *)keyEyesTableView {
    if (!_keyEyesTableView) {
        _keyEyesTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, tableView_Interval + CGRectGetMaxY(self.boutiqueRecommendView.frame), ScreenW, 2000) style:UITableViewStylePlain];
        _keyEyesTableView.dataSource = self;
        _keyEyesTableView.delegate = self;
        _keyEyesTableView.scrollEnabled = NO;
        [_keyEyesTableView registerClass:[HQYOffsetImageCell class] forCellReuseIdentifier:@"123"];
    }
    return _keyEyesTableView;
}

- (HQYHomeKeyEyesModel *)model {
    if (!_model) {
        _model = [[HQYHomeKeyEyesModel alloc] init];
    }
    return _model;
}

#pragma mark - 选择按钮
#pragma mark --选择按钮公共初始化
- (UIButton *)initializeSelectButtonWithTitle:(NSString *)title
                                        image:(UIImage *)image
                                    locationX:(CGFloat)frameX
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.bounds = CGRectMake(0, 0, CGRectGetHeight(self.selectButtonBackgroundView.frame) * 0.7, CGRectGetHeight(self.selectButtonBackgroundView.frame) * 0.7);
    btn.center = CGPointMake(frameX, CGRectGetHeight(self.selectButtonBackgroundView.frame) * 0.5);
    [btn setImage:image forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(clickedSelectBtn:) forControlEvents:UIControlEventTouchUpInside];
    return btn;
}

#pragma mark --选择按钮监听
- (void)clickedSelectBtn:(UIButton *)sender {
    /**< 动画效果 */
    /**< 美食选择 */
    if (sender == self.foodSelectButton) {
        [self emitterAnimationWithImage:@"首页-美食-1"];
    }
    /**< 周边游选择 */
    else if (sender == self.tourSelectButton) {
        [self emitterAnimationWithImage:@"首页-旅游-1"];
    }
    /**< 酒店选择 */
    else if (sender == self.hotelSelectButton) {
        [self emitterAnimationWithImage:@"首页-酒店-1"];
    }
    /**< 我的选择 */
    else if (sender == self.MineSelectButton) {
        [self emitterAnimationWithImage:@"首页-我的-1"];
    }
    [self beginAnimation];
    
    /**< 切换页面 */
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.85 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (sender == self.foodSelectButton) {
            self.tabBarController.selectedIndex = 0;
        }
        else if (sender == self.tourSelectButton) {
            self.tabBarController.selectedIndex = 1;
        }
        else if (sender == self.hotelSelectButton) {
            self.tabBarController.selectedIndex = 3;
        }
        else if (sender == self.MineSelectButton) {
            self.tabBarController.selectedIndex = 4;
        }
    });
}
@end
